﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;

namespace FunstreamTV.Tools
{
    public static class Serializer
    {
        public static string Serialize<T>(T item)
        {
            var ms = new MemoryStream();
            new DataContractJsonSerializer(typeof(T)).WriteObject(ms, item);
            var json = Encoding.UTF8.GetString(ms.ToArray(),0,(int) ms.Length);
            return json;
        }

        public static T Deserialize<T>(string json)
        {
            json = Regex.Replace(json, "\"\":", "\"unknown\":", RegexOptions.IgnorePatternWhitespace);
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
            var result = new DataContractJsonSerializer(typeof (T)).ReadObject(ms);
            return (T) result;
        }
    }
}
